// Detects user activity, will reload the page to proper date if left idle. Updates the clock if left idle.
Activity = {
	init:function(){
		var now = new Date();
		var serverTime = new Date(Clock.toString());
		// record the difference between client js time and server time at time of load. To sense inactivity and out of sync issues.
		Cookie.set('client_server_time_diff',DateTime.diff(now,serverTime,'m'));
		Cookie.set('last_load',DateTime.toString(now));
		$(document).click(function(){
			Activity.query(true);
		});
		$(document).keyup(function(){
			Activity.query(true);
		});
		window.onfocus = function(){
			Activity.query(true);
		};
		Activity.loop();
	},
	loop:function(){
		setTimeout(function(){
			Activity.query(false);
			Activity.loop();
		},10000);
	},
	query:function(isUser){
		var isUser = isUser || false;
		// record the difference from last activity;
		var now = new Date();
		var last = new Date(Cookie.get('last_load'));
		
		//check the clock by checking viewTime with js time. Should fall within range of client_server_time_diff
		var clockDate = new Date(Clock.toString());
		var nowDiff = Math.abs(DateTime.diff(clockDate,now,'m'));
		var originalDiff = Math.abs(+Cookie.get('client_server_time_diff'));
		if(Math.abs(nowDiff - originalDiff) > 1){
			console.warn('updating clock diff of '+(nowDiff - originalDiff)+' min');
			Activity.updateClock();
		}
		
		if(DateTime.diff(last,now,'m') > 10){ // only check if 15 minutes since last action
			// see if day has changed
			var viewDate = new Date($('[name=KalendarToday]').val());
			if(now.getDate() == viewDate.getDate() && now.getMonth() == viewDate.getMonth() && now.getFullYear() == viewDate.getFullYear()){
				/*do nothing*/
			} else {
				// if looking at calendar page specific date. remove date and reload.
				var urlStruct = URL.toStruct();
				if(urlStruct.root.toLowerCase().indexOf('calendar.cfm') >= 0){
					window.history.pushState({},'',urlStruct.root);
				}
				location.reload();
			}
			// update last action, to limit # of checks
			Cookie.set('last_load',DateTime.toString(now));
		}
		
		// update last activity
		if(isUser){
			Cookie.set('last_load',DateTime.toString(now));
			Activity.recordUserActivity();
		}
	},
	recordUserActivity:function(){
		var record = false;
		if(Cookie.get('last_activity') == ""){
			record = true;
		} else {
			var now = new Date();
			var last = new Date(Cookie.get('last_activity'));
			if(DateTime.diff(last,now) > 120){
				record = true;
			}
		}
		if(record){
			Cookie.set('last_activity',DateTime.toString(now),2);
			Ajax.run({
				method:'craftivityService.updateLastActivity',
				onsuccess:function(data){}
			});
		}
	},
	updateClock:function(){
		Ajax.run({
			method:'craftivityService.getDateTime',
			onsuccess:function(data){
				if(data.length == 19){
					var date = new Date(data);
					var dateStruct = DateTime.toStruct(date);
					var weekday = Clock.weekdays[date.getDay()];
					var year = dateStruct.year + '';
					year = year.substring(2,4);
					var hour = dateStruct.hour;
					var ampm = "AM";
					if(hour > 11){
						hour = hour - 12;
						ampm = 'PM';
					}
					if(hour == 0){
						hour = 12;
					}
					Clock.setTime(year,dateStruct.month,dateStruct.date,hour,dateStruct.minute,dateStruct.second,ampm,weekday);
				}
			},
			onfail:function(args){
				console.log("i'm a failure'");
				console.log(args);
				console.log('here are my args');
			}
		});

	}
}
$(document).ready(function(){
	Activity.init();
});